package com.trust.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.trust.agri.util.BeanUtil;
import com.trust.entity.Breed;
import com.trust.entity.Param.BreedListParam;
import com.trust.entity.VO.BreedListVO;
import com.trust.entity.result.DropDownResult;
import com.trust.mapper.BreedMapper;
import com.trust.service.BreedService;
import com.trust.service.DictionaryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class BreedServiceImpl extends ServiceImpl<BreedMapper, Breed> implements BreedService {


    @Resource
    private DictionaryService dictionaryService;


    @Override
    public String getNameById(Integer id) {
        Breed breed = this.getById(id);
        if (null == breed){
            return "";
        }
        return breed.getName();
    }

    @Override
    public List<DropDownResult> dropDown() {
        LambdaQueryWrapper<Breed> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Breed::getEnabled, 1);
        wrapper.orderByDesc(Breed::getId);
        List<Breed> list = this.list(wrapper);
        return BeanUtil.sourceList2targetList(list, DropDownResult.class);
    }


    @Override
    public Page<BreedListVO> list(BreedListParam param) {
        LambdaQueryWrapper<Breed> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getName())){
            wrapper.like(Breed::getName, param.getName());
        }
        if (StringUtils.isNotBlank(param.getSourceNum())){
            wrapper.like(Breed::getSourceNum, param.getSourceNum());
        }
        wrapper.orderByDesc(Breed::getId);
        Page<Breed> page = this.page(new Page<>(param.getPageNum(), param.getPageSize()), wrapper);
        Page<BreedListVO> targetPage = BeanUtil.sourcePage2targetPage(page, BreedListVO.class);
        for (BreedListVO record : targetPage.getRecords()) {
            record.setBreedMaterialName(null == record.getBreedMaterial() ? null : dictionaryService.getNameById(record.getBreedMaterial()));
        }
        return targetPage;
    }
}
